package com.wen.springcloud.dubbo.util;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Wen
 * @date 2025/5/31 03:32
 */
@Component
@Slf4j
public class DistributeLock {

    @Resource
    private RedissonClient redisson;

    public void execute(String key, Runnable runnable) {
        RLock rLock = redisson.getLock(key);
        try {
            // Try to acquire the lock with a wait time and lease time
            boolean isLocked = rLock.tryLock(10, 30, TimeUnit.SECONDS);
            if (isLocked) {
                runnable.run();
            } else {
                log.warn("Failed to acquire lock.");
            }
        } catch (InterruptedException e) {
            log.error("Thread was interrupted", e);
        } finally {
            if (rLock.isHeldByCurrentThread()) {
                rLock.unlock();
                log.info("Lock released.");
            }
        }
    }
}
